#include "settingsdialog.h"
#include "ui_settingsdialog.h"
#include <QWebFrame>
#include <QFile>
#include <QPushButton>
#include <qmath.h>

QString settingsFileName = "settings";
//---------------------------------------------------------------------------------


bool CProgramSettings::SaveFile()
{
    QFile f(settingsFileName);
    QString str;

    str = "lat=" + QString::number(Lat()) +
            "\nlng=" + QString::number(Lng()) +
            "\ntimeZone=" + QString::number(TimeZone()) +
            "\ntithiHint=" + QString::number(TithiHint()) +
            "\nekadashHint=" + QString::number(EkadashHint());
    if (f.open(QIODevice::WriteOnly))
    {
        f.write(str.toLocal8Bit());
        f.close();
    }
    else
        return false;

    return true;
}
//---------------------------

bool CProgramSettings::LoadFile()
{
    QFile f(settingsFileName);
    QString str, paramStr, valStr;

    if (f.open(QIODevice::ReadOnly))
    {
        while (false == f.atEnd())
        {
            str = f.readLine();
            paramStr = str.left(str.indexOf("="));
            if (false == paramStr.isEmpty())
            {
                valStr = str.mid(str.indexOf("=")+1);

                if ("lat" == paramStr)
                    SetLat(valStr.toDouble());
                else if ("lng" == paramStr)
                    SetLng(valStr.toDouble());
                else if ("timeZone" == paramStr)
                    SetTimeZone(valStr.toDouble());
                else if ("tithiHint" == paramStr)
                    SetTithiHint(valStr.toInt());
                else if ("ekadashHint" == paramStr)
                    SetEkadashHint(valStr.toInt());
            }
        }
        f.close();
    }
    else
        return false;
    return true;
}
//---------------------------
//---------------------------------------------------------------------------------


SettingsDialog::SettingsDialog(QWidget *parent) :
    QDialog(parent, Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowSystemMenuHint |
            Qt::WindowMinimizeButtonHint | Qt::WindowCloseButtonHint),
    ui(new Ui::SettingsDialog)
{
    ui->setupUi(this);

    ui->mapWebView->setUrl(QUrl("qrc:/html/google_maps.html"));

    connect(ui->mapWebView->page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()), this, SLOT(mainFrame_javaScriptWindowObjectCleared()));
    connect(ui->buttonBox, SIGNAL(clicked(QAbstractButton*)), this, SLOT(buttonBoxClicked(QAbstractButton*)));
    connect(ui->mapWebView, SIGNAL(loadFinished(bool)), this, SLOT(loadURLFinished(bool)));
    connect(ui->latDoubleSpinBox, SIGNAL(valueChanged(QString)), this, SLOT(OnAnyValueModified(QString)));
    connect(ui->lngDoubleSpinBox, SIGNAL(valueChanged(QString)), this, SLOT(OnAnyValueModified(QString)));
    connect(ui->timeZoneDoubleSpinBox, SIGNAL(valueChanged(QString)), this, SLOT(OnAnyValueModified(QString)));
    connect(ui->timeZoneDoubleSpinBox, SIGNAL(valueChanged(double)), this, SLOT(OnTimeZoneValueModified(double)));

    if (false == LoadSettingsFile())
        qDebug()<<tr("LoadSettingsFile Problem!");

    if (Qt::Unchecked == ui->ekadashiHintCheckBox->checkState())
        ui->tithiHintCheckBox->setDisabled(true);
}
//---------------------------

SettingsDialog::~SettingsDialog()
{
    delete ui;
}
//---------------------------
//---------------------------------------------------------------------------------


void SettingsDialog::SetCoord(double lat, double lng)
{
    ui->latDoubleSpinBox->setValue(lat);
    ui->lngDoubleSpinBox->setValue(lng);
}
//---------------------------

CProgramSettings SettingsDialog::Settings()
{
    CProgramSettings s;
    s.Set(ui->latDoubleSpinBox->value(),ui->lngDoubleSpinBox->value(),ui->timeZoneDoubleSpinBox->value(),
          ui->tithiHintCheckBox->isChecked(), ui->ekadashiHintCheckBox->isChecked());
    return s;
}
//---------------------------
//---------------------------------------------------------------------------------


void SettingsDialog::mainFrame_javaScriptWindowObjectCleared()
{
    ui->mapWebView->page()->currentFrame()->addToJavaScriptWindowObject("qSettingsDialog",this);    
}
//---------------------------

void SettingsDialog::buttonBoxClicked(QAbstractButton* b)
{
    QDialogButtonBox::StandardButton sb = ui->buttonBox->standardButton(b);

    if (sb == QDialogButtonBox::Apply)
    {
        if (false == SaveSettingsFile())
            qDebug()<<tr("SaveSettingsFile Problem!");
        ui->buttonBox->button(QDialogButtonBox::Apply)->setDisabled(true);

        CProgramSettings s = Settings();
        emit ApplySettings(&s);
    }
    else if (sb == QDialogButtonBox::Ok)
    {
        if (false == SaveSettingsFile())
            qDebug()<<tr("SaveSettingsFile Problem!");

        done(QDialog::Accepted);
    }
    else if (sb == QDialogButtonBox::Cancel)
    {
        reject();
    }
}
//---------------------------

void SettingsDialog::loadURLFinished(bool ok)
{
    if (ok)
    {
        QString str;
        str = "map.panTo({lat: " + QString::number(ui->latDoubleSpinBox->value()) +
                ", lng: " + QString::number(ui->lngDoubleSpinBox->value()) + "});";
        ui->mapWebView->page()->mainFrame()->/*documentElement().*/evaluateJavaScript(str);
    }
}
//---------------------------

void SettingsDialog::OnAnyValueModified(QString str)
{
    ui->buttonBox->button(QDialogButtonBox::Apply)->setEnabled(true);
}
//---------------------------

void SettingsDialog::OnTimeZoneValueModified(double v)
{
    if ((v - qFloor(v/0.25)*0.25) >= 0.125)
    {
        v -= v - qCeil(v/0.25)*0.25;
        ui->timeZoneDoubleSpinBox->setValue(v);
    }
    else
    {
        v -= v - qFloor(v/0.25)*0.25;
        ui->timeZoneDoubleSpinBox->setValue(v);
    }
}
//---------------------------

void SettingsDialog::on_ekadashiHintCheckBox_stateChanged(int arg1)
{
    if (Qt::Checked == arg1)
        ui->tithiHintCheckBox->setEnabled(true);
    else if (Qt::Unchecked == arg1)
    {
        ui->tithiHintCheckBox->setEnabled(false);
        ui->tithiHintCheckBox->setChecked(false);
    }
    ui->buttonBox->button(QDialogButtonBox::Apply)->setEnabled(true);
}
//---------------------------

void SettingsDialog::on_tithiHintCheckBox_stateChanged(int arg1)
{
    ui->buttonBox->button(QDialogButtonBox::Apply)->setEnabled(true);
}
//---------------------------
//---------------------------------------------------------------------------------


bool SettingsDialog::SaveSettingsFile()
{
    CProgramSettings s = Settings();
    return s.SaveFile();
}
//---------------------------

bool SettingsDialog::LoadSettingsFile()
{
    CProgramSettings s = Settings();
    bool r = s.LoadFile();
    if (false == r)
        s.SetDefaults();

    ui->latDoubleSpinBox->setValue(s.Lat());
    ui->lngDoubleSpinBox->setValue(s.Lng());
    ui->timeZoneDoubleSpinBox->setValue(s.TimeZone());
    ui->ekadashiHintCheckBox->setChecked(s.EkadashHint());
    ui->tithiHintCheckBox->setChecked(s.TithiHint());    

    return r;
}
//---------------------------
//---------------------------------------------------------------------------------

